/**
 * Main application entry point
 */

import { wsManager } from "./websocket.js";
import { ui } from "./ui.js";
class ChatApp {
    constructor() {
        this.isInitialized = false;
        this.initializationPromise = null;
    }

    /**
     * Initialize the application
     */
    async initialize() {
        if (this.isInitialized) {
            return;
        }

        if (this.initializationPromise) {
            return this.initializationPromise;
        }

        this.initializationPromise = this._performInitialization();
        return this.initializationPromise;
    }

    /**
     * Perform the actual initialization
     */
    async _performInitialization() {
        try {
            console.log('Initializing Chat App...');

            // Show loading screen
            this.showLoading();

            // Initialize components
            await this.initializeComponents();

            // Setup global error handling
            this.setupErrorHandling();

            // Setup keyboard shortcuts
            this.setupKeyboardShortcuts();

            // Setup beforeunload handling
            this.setupBeforeUnload();

            // Request notification permission
            await this.requestNotificationPermission();

            // Hide loading screen
            this.hideLoading();

            this.isInitialized = true;
            console.log('Chat App initialized successfully');

        } catch (error) {
            console.error('Failed to initialize Chat App:', error);
            this.showError('Failed to initialize application. Please refresh the page.');
        }
    }

    /**
     * Initialize application components
     */
    async initializeComponents() {
        // Test server connection
        const isServerHealthy = await this.testServerConnection();
        if (!isServerHealthy) {
            throw new Error('Server is not responding');
        }

        // Initialize router (already done in router.js)
        console.log('Router initialized');

        // Initialize WebSocket manager (already done in websocket.js)
        console.log('WebSocket manager initialized');

        // Initialize UI manager (already done in ui.js)
        console.log('UI manager initialized');

        // Load user preferences
        this.loadUserPreferences();
    }

    /**
     * Test server connection
     */
    async testServerConnection() {
        try {
            const isHealthy = await api.healthCheck();
            return isHealthy;
        } catch (error) {
            console.error('Server health check failed:', error);
            return false;
        }
    }

    /**
     * Load user preferences from storage
     */
    loadUserPreferences() {
        const preferences = storage.get('userPreferences', {
            theme: 'light',
            notifications: true,
            soundNotifications: true,
            nickname: ''
        });

        // Apply theme
        this.applyTheme(preferences.theme);

        // Store preferences globally
        window.userPreferences = preferences;
    }

    /**
     * Save user preferences to storage
     */
    saveUserPreferences(preferences) {
        window.userPreferences = { ...window.userPreferences, ...preferences };
        storage.set('userPreferences', window.userPreferences);
    }

    /**
     * Apply theme
     */
    applyTheme(theme) {
        document.body.setAttribute('data-theme', theme);
    }

    /**
     * Setup global error handling
     */
    setupErrorHandling() {
        // Handle uncaught errors
        window.addEventListener('error', (event) => {
            console.error('Uncaught error:', event.error);
            this.showError('An unexpected error occurred. Please refresh the page if problems persist.');
        });

        // Handle unhandled promise rejections
        window.addEventListener('unhandledrejection', (event) => {
            console.error('Unhandled promise rejection:', event.reason);
            this.showError('An unexpected error occurred. Please refresh the page if problems persist.');
        });

        // Handle WebSocket errors
        wsManager.on('error', (error) => {
            console.error('WebSocket error:', error);
            showToast('Connection error occurred', 'error');
        });

        wsManager.on('reconnectFailed', () => {
            this.showError('Unable to reconnect to the server. Please refresh the page.');
        });
    }

    /**
     * Setup keyboard shortcuts
     */
    setupKeyboardShortcuts() {
        document.addEventListener('keydown', (event) => {
            // Ctrl/Cmd + K: Focus message input
            if ((event.ctrlKey || event.metaKey) && event.key === 'k') {
                event.preventDefault();
                const messageInput = document.getElementById('message-input');
                if (messageInput && !messageInput.disabled) {
                    messageInput.focus();
                }
            }

            // Escape: Close modals
            if (event.key === 'Escape') {
                this.closeModals();
            }

            // Ctrl/Cmd + Enter: Send message (alternative to Enter)
            if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') {
                const messageInput = document.getElementById('message-input');
                if (messageInput === document.activeElement) {
                    event.preventDefault();
                    ui.sendMessage();
                }
            }
        });
    }

    /**
     * Setup beforeunload handling
     */
    setupBeforeUnload() {
        window.addEventListener('beforeunload', (event) => {
            // Clean up WebSocket connection
            if (wsManager.isConnected) {
                wsManager.leaveRoom();
                wsManager.disconnect();
            }

            // If user is in a room, show confirmation
            if (ui.currentRoom && ui.currentUser) {
                event.preventDefault();
                event.returnValue = 'Are you sure you want to leave? You will be disconnected from the chat room.';
                return event.returnValue;
            }
        });
    }

    /**
     * Request notification permission
     */
    async requestNotificationPermission() {
        if ('Notification' in window && Notification.permission === 'default') {
            try {
                const permission = await Notification.requestPermission();
                console.log('Notification permission:', permission);
            } catch (error) {
                console.log('Notification permission request failed:', error);
            }
        }
    }

    /**
     * Close all open modals
     */
    closeModals() {
        const modals = document.querySelectorAll('.modal:not(.hidden)');
        modals.forEach(modal => {
            modal.classList.add('hidden');
        });

        const errorDisplay = document.getElementById('error-display');
        if (errorDisplay && !errorDisplay.classList.contains('hidden')) {
            errorDisplay.classList.add('hidden');
        }
    }

    /**
     * Show loading screen
     */
    showLoading(message = 'Loading...') {
        const loadingScreen = document.getElementById('loading-screen');
        const loadingText = loadingScreen?.querySelector('p');
        
        if (loadingText) {
            loadingText.textContent = message;
        }
        
        if (loadingScreen) {
            loadingScreen.classList.remove('hidden');
        }
    }

    /**
     * Hide loading screen
     */
    hideLoading() {
        const loadingScreen = document.getElementById('loading-screen');
        if (loadingScreen) {
            loadingScreen.classList.add('hidden');
        }
    }

    /**
     * Show error message
     */
    showError(message, details = '') {
        const errorDisplay = document.getElementById('error-display');
        const errorMessage = document.getElementById('error-message');
        
        if (errorMessage) {
            errorMessage.innerHTML = `
                <strong>${sanitizeHtml(message)}</strong>
                ${details ? `<br><small>${sanitizeHtml(details)}</small>` : ''}
            `;
        }
        
        if (errorDisplay) {
            errorDisplay.classList.remove('hidden');
        }

        // Setup error close handler
        const errorCloseBtn = document.getElementById('error-close');
        if (errorCloseBtn) {
            errorCloseBtn.onclick = () => {
                errorDisplay.classList.add('hidden');
            };
        }
    }

    /**
     * Get application status
     */
    getStatus() {
        return {
            initialized: this.isInitialized,
            router: router.getCurrentRoute(),
            websocket: wsManager.getStatus(),
            user: ui.currentUser,
            room: ui.currentRoom
        };
    }

    /**
     * Enable debug mode
     */
    enableDebugMode() {
        window.chatAppDebug = {
            app: this,
            router,
            wsManager,
            ui,
            api,
            utils: {
                storage,
                sessionStorage,
                showToast,
                copyToClipboard,
                formatTime,
                sanitizeHtml
            }
        };
        
        console.log('Debug mode enabled. Access via window.chatAppDebug');
    }
}

// Create global app instance
const app = new ChatApp();

// Initialize when DOM is loaded
document.addEventListener('DOMContentLoaded', async () => {
    try {
        await app.initialize();
        
        // Enable debug mode in development
        if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
            app.enableDebugMode();
        }
        
    } catch (error) {
        console.error('Failed to start application:', error);
    }
});

// Export for global access
window.app = app;